package hn.cch.druid.repository;

import hn.cch.druid.query.Where;
import org.springframework.data.jpa.repository.query.QueryUtils;
import org.springframework.data.jpa.repository.support.JpaEntityInformation;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.io.Serializable;
import java.util.List;

/**
 * @author CCH
 * @version 2018.08.30
 */
public class DruidRepositoryImpl<T, ID extends Serializable> extends
        SimpleJpaRepository<T, ID> implements DruidRepository<T, ID> {

    private JpaEntityInformation<T, ?> entityInformation;
    private EntityManager entityManager;


    public DruidRepositoryImpl(JpaEntityInformation<T, ?> entityInformation,
                               EntityManager entityManager) {
        super(entityInformation, entityManager);

        this.entityInformation = entityInformation;
        this.entityManager = entityManager;

    }

    /**
     * 条件查询
     * @param where
     * @return
     */

    @Override
    public List<T> findWhere(Where where) {
        //拼接SQL
        StringBuffer buffer = new StringBuffer();
        buffer.append(QueryUtils.getQueryString("FROM ", entityInformation
                .getEntityName()));//表
        buffer.append(where.toString());//条件
        //查询
        Query query = entityManager.createQuery(buffer.toString());
        return query.getResultList();
    }

}
